﻿using IOA.MES.Client.Common;
using IOA.MES.Client.Models.Response;
using IOA.MES.Client.Settings;
using NLog;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Diagnostics;
using System.Reflection;
using System.Windows.Input;
using IOA.MES.Client.Common.SocketUtils;
using System.Windows.Media;

namespace IOA.MES.Client.Laminator
{
    /// <summary>
    /// LaminatorIndex.xaml 的交互逻辑
    /// </summary>
    public partial class LaminatorIndex : System.Windows.Window
    {
        private List<ViaSiteRecord> _records { get; set; } = new List<ViaSiteRecord>();
        private string printer = BaseEnv.GetStorage("叠层条码");
        private int printCount = Convert.ToInt32(BaseEnv.GetStorage("叠层条码数量") ?? "0");
        private Models.Response.Label label = null;
        private int downloadStatus = 0;
        private SocketClient sockClient = null;

        public LaminatorIndex()
        {
            InitializeComponent();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            txtTrueName.Text = BaseEnv.UserInfo.TrueName;
            InitDuties();
            InitMachines();
            InitRecords();
            InitForm();
        }

        #region 初始化数据
        public void InitDuties()
        {
            var duties = BaseEnv.InvokeApi<QueryDutiesResponse>("/api/Auth/QueryDuties", new { WorkshopCode = BaseEnv.WorkshopCode }).Data.Duties;

            cbDuties.ItemsSource = duties;
            cbDuties.DisplayMemberPath = "DutyName";
            cbDuties.SelectedValuePath = "DutyId";

            if (duties.Any())
            {
                cbDuties.SelectedIndex = 0;
            }
        }

        public void InitMachines()
        {
            var machines = BaseEnv.InvokeApi<QueryMachinesResponse>("/api/Machine/QueryMachines", new { WorkshopCode = BaseEnv.WorkshopCode, MachineType = MachineType.Laminator }).Data.Machines;
            cbMachines.ItemsSource = machines;
            cbMachines.DisplayMemberPath = "MachineName";
            cbMachines.SelectedValuePath = "MachineId";

            if (machines.Any(_ => _.MachineId == BaseEnv.MachineId))
            {
                cbMachines.SelectedIndex = machines.FindIndex(_ => _.MachineId == BaseEnv.MachineId);
            }
            else
            {
                CommonMessage.Alert(this, "请先在系统设置中重新选择设备\r\nPlease reselect the device in the system settings now"); ;
                new SettingsIndex().ShowDialog();
            }
        }

        private void InitRecords()
        {
            new TaskFactory().StartNew(() =>
            {
                Thread.Sleep(100);
                Dispatcher.Invoke(new Action(() =>
                {
                    var response = BaseEnv.InvokeApi<QueryViaSiteRecordsResponse>("/api/Machine/QueryViaSiteRecords", new { DutyId = Convert.ToInt32(cbDuties.SelectedValue), SiteType = SiteType.Laminated, MachineId = Convert.ToInt32(cbMachines.SelectedValue) });
                    if (response.ErrCode != 200)
                    {
                        CommonMessage.Alert(this, response.ErrMsg);
                        return;
                    }
                    _records.Clear();
                    _records.AddRange(response.Data.Records);
                    _records.ForEach(_ => _.No = _records.Count - _records.IndexOf(_));
                    lbTotal.Content = response.TotalCount;
                    BindGridRecords();
                }));
            });
        }

        private void InitForm()
        {
            txtCode.Text = "";
            txtCode.Focus();
        }

        private void BindGridRecords()
        {
            gridRecords.ItemsSource = null;
            gridRecords.ItemsSource = _records;
        }


        private void TryConnectSocket()
        {
            var ipAddress = BaseEnv.GetStorage("LaminatorIpAddress") ?? string.Empty;
            var port = BaseEnv.GetStorage("LaminatorPort") ?? string.Empty;
            if (!string.IsNullOrWhiteSpace(ipAddress) && !string.IsNullOrWhiteSpace(port))
            {
                sockClient = new SocketClient(this, ipAddress, Convert.ToInt32(port), OnTcpStatusChange, OnDataReceived, new List<byte>(), 0);
                sockClient.Connect();
            }
        }
        #endregion

        /// <summary>
        /// TCP状态变化
        /// </summary>
        public void OnTcpStatusChange(bool connected)
        {
            Dispatcher.Invoke(new Action(() =>
            {
                lbStatus.Content = connected ? "已连接" : "已断开";
                if (connected)
                {
                    lbStatus.Foreground = new SolidColorBrush(Colors.Green);
                }
                else
                {
                    lbStatus.Foreground = new SolidColorBrush(Colors.Red);
                }
            }));
        }

        /// <summary>
        /// 接收TCP小时
        /// </summary>
        public void OnDataReceived(List<byte> data)
        {
            Thread.Sleep(1000);
            sockClient.Send(new List<byte> { 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 });
        }

        /// <summary>
        /// 文本框回车
        /// </summary>
        private void txtCode_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter && !string.IsNullOrWhiteSpace(txtCode.Text))
            {
                ViaSite();
            }
        }

        /// <summary>
        /// 组件条码扫描
        /// </summary>
        private void ViaSite()
        {
            var response = BaseEnv.InvokeApi<ViaSiteResponse>("/api/Machine/ViaSite", new
            {
                SiteType = SiteType.Laminated,
                DutyId = Convert.ToInt32(cbDuties.SelectedValue),
                MachineId = Convert.ToInt32(cbMachines.SelectedValue),
                Code = txtCode.Text.Trim()
            });
            if (response.ErrCode != 200)
            {
                mediaElResult.Source = new Uri($"{BaseEnv.LocalDirectory}\\res\\audio\\Fail.wav");
                mediaElResult.Play();
                CommonMessage.Alert(this, response.ErrMsg);
                InitForm();
                return;
            }
            CommonMessage.Log(LogLevel.Info, $"过站成功：{txtCode.Text.Trim()}");

            mediaElResult.Source = new Uri($"{BaseEnv.LocalDirectory}\\res\\audio\\Success.wav");
            mediaElResult.Play();

            lbWorkOrderNo.Content = response.Data.ViaSiteRecord.WorkOrderNo;
            gridBoms.ItemsSource = null;
            gridBoms.ItemsSource = response.Data.Boms;

            if (response.Data.DutyId != Convert.ToInt32(cbDuties.SelectedValue))
            {
                cbDuties.SelectedValue = response.Data.DutyId;
            }
            else
            {
                response.Data.ViaSiteRecord.No = _records.Count + 1;
                _records.Insert(0, response.Data.ViaSiteRecord);
                lbTotal.Content = response.Data.Output;
                BindGridRecords();
            }
            InitForm();
        }

        private void cb_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            InitRecords();
        }

        private void Menu_Click(object sender, RoutedEventArgs e)
        {
            switch (((MenuItem)sender).Name)
            {
                case "btnSettings":
                    new SettingsIndex().ShowDialog();
                    break;
                case "btnMissingRecords":
                    new MissingSiteRecord(Convert.ToInt32(cbMachines.SelectedValue)).Show();
                    break;
                case "btnPlcSettings":
                    if (new WinPlcSetting().ShowDialog() == true)
                    {
                        if (sockClient != null)
                        {
                            sockClient.Close();
                            Thread.Sleep(1000);
                        }
                        TryConnectSocket();
                    }
                    break;
                case "btnPrinterSetting":
                    if (new WinLaminatorPrinterSetting().ShowDialog() == true)
                    {
                        printer = BaseEnv.GetStorage("叠层条码");
                        printCount = Convert.ToInt32(BaseEnv.GetStorage("叠层条码数量") ?? "0");
                    }
                    break;
                case "btnLogout":
                    new LoginWindow(false).Show();
                    this.Hide();
                    break;
                case "btnRePrinte":
                    new WinLaminatorRePrint().ShowDialog();
                    break;
                case "btnAbout":
                    MessageBox.Show($"AISUNMes Product Version:{FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().Location).ProductVersion}");
                    break;
            }
        }

        private void Window_Closed(object sender, EventArgs e)
        {
            Environment.Exit(0);
        }
    }
}
